package com.link.base.base.position.controller;

import com.alibaba.fastjson.JSON;
import com.link.base.user.model.CoreUser;
import com.link.base.base.position.model.Position;
import com.link.base.base.position.service.PositionService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.interceptor.SecurityInterceptor;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.query.Sorter;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.JsonUtil;
import com.link.core.util.RedisUtil;
import com.link.core.util.UserUtil;
import com.link.core.util.redisclient.LinkRedisClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author unknown
 * @date unknown
 * @comments 职位结构请求处理
 */
@Controller("BusPositionController")
@RequestMapping("/link/position")
public class PositionController extends BasicController<Position> {

    @Resource
    private PositionService positionService;

    @Override
    public BasicService<Position> getBasicService() throws Exception {
        return positionService;
    }

    /**
     * 加载树
     */
    @RequestMapping(value = "/treelist", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> treelist(QueryParams qps, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Position root = positionService.queryRoot(new Position());
            positionService.queryTreeByRoot(root);
            result.put("success", true);
            result.put("tree", true);
            //传根节点
            result.put("list", root);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("list", new Position());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 加载结构框图树
     */
    @RequestMapping(value = "/treelist/{initPosId}")
    @ResponseBody
    public Position treelist(@PathVariable Long initPosId, QueryParams qps, HttpSession session,
                             HttpServletRequest request, HttpServletResponse response) {
        Position root = new Position();
        try {
            root.setId(initPosId);
            root = positionService.queryById(root);
            positionService.queryTreeByRoot1(root);
        } catch (Exception e) {
            LCLogger.withException(e);
        }
        return root;
    }

    /**
     * 选择父对象时的picklist
     */
    @RequestMapping(value = "/parentPicklist", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> parentPicklist(Position entity, QueryParams qps, HttpSession session,
                                              HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            qps.setAttr3(String.valueOf(entity.getId()));
            //按创建时间来排序
            qps.addSorter(new Sorter("created", Sorter.DIR_DESC));
            Position t = (Position) BasicModel.transformClass(Position.class, qps);
            //设置安全性
            t.preDealSecurity(request);
            List<Position> list = positionService.queryPositionListRemoveIdAndChildrenPage(t);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount(((BasicModel) t), list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<Position>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 通用picklist
     */
    @RequestMapping(value = "/picklist", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> picklist(QueryParams qps, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Position t = (Position) BasicModel.transformClass(Position.class, qps);
            //设置安全性
            t.preDealSecurity(request);
            List<Position> list = positionService.queryByExamplePage(t);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount(((BasicModel) t), list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<Position>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 通用picklist
     */
    @RequestMapping(value = "/userPostnPicklist", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> userPostnPicklist(QueryParams qps, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            Position t = (Position) BasicModel.transformClass(Position.class, qps);
            //设置安全性
            t.preDealSecurity(request);
            List<Position> list = positionService.queryUserPostnById(t);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount(((BasicModel) t), list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<Position>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 获取登录用户的所有职位
     */
    @RequestMapping(value = "/postnOfUser")
    @ResponseBody
    public Object list(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        QueryParams qps = new QueryParams();
        Long userId = UserUtil.getUser().getId();
        if (userId == null) {
            userId = Long.parseLong("noMactchId");
        }
        qps.setPageFlag(false);
        List<Position> list = null;
        try {
            Position t = (Position) BasicModel.transformClass(Position.class, qps);
            t.setUserId(userId);
            list = positionService.queryByUserPage(t);
        } catch (Exception e) {
            LCLogger.withException(e);
            list = new ArrayList<Position>();
        }
        return list;
    }

    /**
     * 修改session中的职位信息
     */
    @RequestMapping(value = "/changeLoginPostn")
    @ResponseBody
    public Map<String, Object> changeLoginPostn(Position entity, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        LinkRedisClient jedis = null;
        try {
            Position position = positionService.queryById(entity);
            CoreUser user = UserUtil.getUser();
            if (user != null && position != null) {
                user.setPostnId(position.getId());
                user.setPostnName(position.getText());
                user.setDeptId(position.getDeptId());
                user.setDeptName(position.getDeptName());
                user.setOrgId(position.getOrgId());
                user.setOrgName(position.getOrgName());
                user.setAcctId(position.getDealerId());
                user.setAcctName(position.getDealerName());
//              session.setAttribute("UserContext", user);
                //更新到redis中
                String userJson = JsonUtil.toString(user);
                String token = SecurityInterceptor.token.get();
                String tokenKey = SecurityInterceptor.TOKEN_PREFIX + token;
                jedis = RedisUtil.getJedis();
                long expires = jedis.ttl(tokenKey);
                if (expires < 0) {
                    jedis.setex(tokenKey, 60 * 60 * 2, userJson);
                } else {
                    jedis.setex(tokenKey, (int) expires, userJson);
                }
                SecurityInterceptor.tempUser.set(user);
                String key = SecurityInterceptor.TOKEN_PREFIX + token;
                String userStr = JSON.toJSONString(user);
                SecurityInterceptor.setUserToken(key, userStr);
            } else {
                throw new ServiceException("POSITION-014");
            }
            result.put("user", user);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        } finally {
            RedisUtil.returnResource(jedis);
        }
        return result;
    }

    /**
     * 根据ID删除该记录以及其子对象
     */
    @RequestMapping(value = "/deleteWithChildById")
    @ResponseBody
    public Map<String, Object> deleteWithChildById(@JsonParam Position entity, HttpSession session,
                                                   HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("deleteWithChildById")
                .withMessage("根据ID删除该记录以及其子对象信息...").flush();
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            beforDelete(entity, request);
            checkData(entity, request);
            String base = "base";
            if (!checkExistDataCache(base, session, entity)) {
                throw new ServiceException("POSITION-031");
            }
            positionService.deleteWithChildById(entity);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }
}
